package com.yh.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.yh.bean.User;
import com.yh.service.UserService;
import com.yh.utils.ValidateCode;

@Controller
public class UserController {
	@Autowired
	private UserService userServiceImpl;

	    //后台管理页面删除用户
	    @RequestMapping("/deleteUser.se")
	    @ResponseBody
	    public String delete(int uid){
	    	userServiceImpl.deleteUser(uid);
	    	System.out.println("控制器层删除用户");
			return "success";
	    }
	
	    //后台管理页面修改用户身份状态和发帖状态 
	    @RequestMapping("/updateUser.on")
	    @ResponseBody
	    public String updateUser(User user,int uid){
	    	System.out.println("控制器uid="+uid);
	    	user.setUid(uid);
	    	boolean success=userServiceImpl.updateUser(user);
			return "success";
	    }
	
	    //后台根据用户姓名模糊查询
	    @RequestMapping("/query4.se")
	    @ResponseBody
	    public List<User> queryUser4(User user,String realName){
	    	//System.out.println("控制层realName="+realName);
	    	user.setRealName(realName);
	    	List<User> userList=userServiceImpl.queryUser4(user);
	    	//System.out.println(userList);
			return userList;
	    }
	
	    //后台查询用户数据并展示
	    @RequestMapping("/query3.se")
	    @ResponseBody
	    public Map queryUser3(int currentPage){
	    	//System.out.println("控制层="+currentPage);
            Map map=userServiceImpl.queryUser3(currentPage);	    	
	    	return map;
	    }
	
	    //用户注册添加用户
		@RequestMapping("/register")
		@ResponseBody
		public boolean addUser(User user,MultipartFile photo2,HttpServletRequest request,
				String birthDay2,String uname,String realName,String password,String email,String phone){
			//System.out.println("控制器层");
			//System.out.println("*****************birthday"+user.getBirthDay());
			user.setBirthDay(birthDay2);
			//System.out.println("user.setBirthDay(birthDay2)");
			//判断图片是否为空
			if(photo2!=null){
				String realpath=request.getServletContext().getRealPath("/images");
				String imagePath="images/"+photo2.getOriginalFilename();
				String uploadpath=realpath+"/"+photo2.getOriginalFilename();
				user.setPhoto(imagePath);
				try {
					FileUtils.copyInputStreamToFile(photo2.getInputStream(),new File(uploadpath));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			} 
			
			if(uname==""|realName==""|password==""|email==""|phone==""){
				return false;
			}else{
				int count=userServiceImpl.addUser(user);
			}
			return true;
		}
	
	
	    //用户登陆查询用户与数据库登录名和密码是否对应
		@RequestMapping("/query2")
		@ResponseBody
		public String queryUser(User user, String code, Model model,
				HttpSession session, HttpServletRequest request,
				HttpServletResponse response) throws Exception {
			String sessionCode = (String) request.getSession().getAttribute("code");// 得到session中的正确验证码
			String uname=user.getUname();
			//System.out.println(user.getUname());
			User user2 = userServiceImpl.queryUser(user);
		    session=request.getSession();
		    session.setAttribute("user", user2);
			//System.out.println("控制器层");

			if (user2 != null && code != null && code.equalsIgnoreCase(sessionCode)&&code.equals(sessionCode)) { // 登录验证成功
				/*request.getSession().setAttribute("loginUser", user2);
				response.sendRedirect(request.getContextPath() + "/success.jsp");
				long endTime = System.currentTimeMillis();*/ // 结束时间
				
				return "true";
			} else {// 登录验证失败
				/*request.getSession().setAttribute("error", "登录出错,请检查登录信息是否正确！");
				request.getRequestDispatcher("/error.jsp").forward(request,
						response);*/ // 转到出错页面
				return "false";
			}
		}
	
	/** 
	 * 响应验证码页面 
	 * @return 
	 */  
	@RequestMapping("/validateCode")  
	public String validateCode(HttpServletRequest request,HttpServletResponse response) throws Exception{  
	    // 设置响应的类型格式为图片格式  
	    response.setContentType("image/jpeg");  
	    //禁止图像缓存。  
	    //response.setHeader("Pragma", "no-cache");  
	    response.setHeader("Cache-Control", "no-cache");  
	    response.setDateHeader("Expires", 0);  
	  
	    HttpSession session = request.getSession();  
	  
	    ValidateCode vCode = new ValidateCode(120,40,5,100);  
	    session.setAttribute("code", vCode.getCode());  
	    vCode.write(response.getOutputStream());  
	    
	    /*String code = request.getParameter("code");  
	    //HttpSession session = request.getSession();  
	    String sessionCode = (String) session.getAttribute("code");  
	    if (!StringUtils.equalsIgnoreCase(code, sessionCode)) {  //忽略验证码大小写  
	        throw new RuntimeException("验证码对应不上code=" + code + "  sessionCode=" + sessionCode); 
	    }*/
	    return null;  
	} 
	
	//用户忘记密码修改数据库密码
    @RequestMapping("/update")
    @ResponseBody
    public boolean updatePwd(User user,String password3,String phone,String email){
		System.out.println("我要修改密码了！");
		System.out.println(user.getRealName());//注意，之后前台ajax传过来的值通过user对象的get方法可以获取到，其他获取不到
		User user2=userServiceImpl.queryUser2(user);
		/*user2.setPhone(phone);
		user2.setEmail(email);*/
		user2.setPhone(user.getPhone());
		user2.setEmail(user.getEmail());
		user2.setPassword(password3);
    	int count=userServiceImpl.updatePwd(user2);
    	return true;
    }
    
}
